#include "savework.h"
#include "notedb.h"

SaveWork::SaveWork(QObject *parent)
    : QThread{parent}
{
    delayTime();
    qDebug() << "SaveWork created.";
}

void SaveWork::setBeginTime(const QDateTime &newBeginTime)
{
    beginTime = newBeginTime;
}

bool SaveWork::getIsRunning() const
{
    return isRunning;
}

void SaveWork::doSaveWork(const ImageInfo &info)
{
    this->info = info;

    if(getIsRunning()){
        delayTime();
    }else{
        start();
    }
}

void SaveWork::delayTime()
{
    beginTime = QDateTime::currentDateTime().addSecs(DELAY_SECOND);
}

void SaveWork::run()
{
    qDebug() << "SaveWork begin.";
    isRunning = true;

    while(true){
        auto now = QDateTime::currentDateTime();

        if(now > beginTime){
            break;
        }

//        qDebug() << "sleep";
        QThread::sleep(DELAY_SECOND);

    }

    NoteDB::insertOrUpdate(this->info);

    isRunning = false;
    delayTime();
    qDebug() << "doSaveWork ok";
}
